<template>
  <div class="orders-container">
    <el-card class="orders-card">
      <template #header>
        <div class="card-header">
          <h3>我的订单</h3>
        </div>
      </template>

      <!-- 订单状态标签 -->
      <div class="status-tabs">
        <el-tabs v-model="activeStatus" @tab-click="handleStatusChange">
          <el-tab-pane label="全部" name="all" />
          <el-tab-pane label="待付款" name="待付款" />
          <el-tab-pane label="已付款" name="已付款" />
          <el-tab-pane label="已发货" name="已发货" />
          <el-tab-pane label="已完成" name="已完成" />
          <el-tab-pane label="已取消" name="已取消" />
        </el-tabs>
      </div>

      <!-- 订单列表 -->
      <div v-if="orders.length" class="orders-list">
        <el-card v-for="order in orders" :key="order.id" class="order-item">
          <template #header>
            <div class="order-header">
              <div class="order-info">
                <span>订单编号：{{ order.id }}</span>
                <span>下单时间：{{ order.createTime }}</span>
              </div>
              <el-tag :type="getStatusType(order.status)">{{ order.status }}</el-tag>
            </div>
          </template>

          <!-- 订单商品 -->
          <div class="order-content">
            <div v-for="item in order.items" :key="item.id" class="order-drug">
              <img :src="item.drug.image" class="drug-image">
              <div class="drug-info">
                <h4>{{ item.drug.name }}</h4>
                <p>规格：{{ item.drug.specification }}</p>
                <p>数量：{{ item.quantity }}</p>
              </div>
              <div class="drug-price">
                <span class="price">¥{{ item.price }}</span>
              </div>
            </div>
          </div>

          <!-- 订单底部 -->
          <div class="order-footer">
            <div class="order-total">
              <span>共{{ order.items.length }}件商品</span>
              <span class="total-price">合计：¥{{ order.total.toFixed(2) }}</span>
            </div>
            <div class="order-actions">
              <el-button 
                v-if="order.status === '待付款'"
                type="primary"
                size="small"
                @click="handlePay(order)"
              >
                立即付款
              </el-button>
              <el-button 
                v-if="order.status === '待付款'"
                type="danger"
                size="small"
                @click="handleCancel(order)"
              >
                取消订单
              </el-button>
              <el-button 
                v-if="order.status === '已发货'"
                type="success"
                size="small"
                @click="handleConfirm(order)"
              >
                确认收货
              </el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 空状态 -->
      <el-empty v-else description="暂无订单" />

      <!-- 分页 -->
      <div class="pagination" v-if="orders.length">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrders, updateOrder } from '../api'

const activeStatus = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const orders = ref([])

const getStatusType = (status) => {
  const map = {
    '待付款': 'warning',
    '已付款': 'success',
    '已发货': 'primary',
    '已完成': 'success',
    '已取消': 'info'
  }
  return map[status] || 'info'
}

const loadOrders = async () => {
  try {
    const userId = JSON.parse(localStorage.getItem('user')).id
    const params = {
      userId,
      page: currentPage.value,
      pageSize: pageSize.value,
      status: activeStatus.value === 'all' ? undefined : activeStatus.value
    }
    const { data, total: totalCount } = await getOrders(params)
    orders.value = data
    total.value = totalCount
  } catch (error) {
    ElMessage.error('获取订单失败')
  }
}

const handleStatusChange = () => {
  currentPage.value = 1
  loadOrders()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadOrders()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadOrders()
}

const handlePay = async (order) => {
  try {
    // 这里应该跳转到支付页面
    ElMessage.success('支付成功')
    await updateOrder(order.id, { status: '已付款' })
    loadOrders()
  } catch (error) {
    ElMessage.error('支付失败')
  }
}

const handleCancel = async (order) => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await updateOrder(order.id, { status: '已取消' })
    ElMessage.success('订单已取消')
    loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消订单失败')
    }
  }
}

const handleConfirm = async (order) => {
  try {
    await ElMessageBox.confirm('确认已收到商品？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await updateOrder(order.id, { status: '已完成' })
    ElMessage.success('确认收货成功')
    loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('确认收货失败')
    }
  }
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.orders-container {
  min-height: 100%;
}

.orders-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #333;
}

.status-tabs {
  margin-bottom: 20px;
}

.order-item {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-info {
  display: flex;
  gap: 20px;
  color: #666;
  font-size: 14px;
}

.order-content {
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
}

.order-drug {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 10px;
}

.drug-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.drug-info {
  flex: 1;
}

.drug-info h4 {
  margin: 0 0 8px;
  font-size: 14px;
  color: #333;
}

.drug-info p {
  margin: 4px 0;
  font-size: 12px;
  color: #666;
}

.drug-price {
  min-width: 100px;
  text-align: right;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
}

.order-total {
  color: #666;
  font-size: 14px;
}

.total-price {
  margin-left: 20px;
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 